﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Eacademy.Domain.Abstractions;
using Eacademy.Domain.Models;
using Eacademy.Library.Actions;
using Eacademy.Library.Membership;

namespace Eacademy.Areas.Student.Controllers
{
    [ProfileControllerFilter]
    public class QuizzesController : Controller
    {
        private const int DefaultPageSize = 10;

        private IQuizRepository _quizRepository;
        private ISubjectRepository _subjectRepository;
        private IMentorRepository _mentorRepository;
        private IStudentRepository _studentRepository;

        public QuizzesController(IQuizRepository quizRepository, ISubjectRepository subjectRepository, IMentorRepository mentorRepository, IStudentRepository studentRepository)
        {
            _quizRepository = quizRepository;
            _subjectRepository = subjectRepository;
            _mentorRepository = mentorRepository;
            _studentRepository = studentRepository;

        }

        CustomMembershipProvider provider = (CustomMembershipProvider)Membership.Provider;

        //
        // GET: /Student/Quizzes/

        public ActionResult Index(int id, int? page, int mentoruserid = 0)
        {
            if (mentoruserid < 1)
            {
                return Redirect("/student/subjects");
            }
            int currentPageIndex = page.HasValue ? (page.Value <= 0 ? 0 : page.Value - 1) : 0;
            QuizListViewModel quizListViewModel = new QuizListViewModel();
            int totalcount = 0;
            List<QuizViewModel> quizViewModels = _quizRepository.GetStudentQuizzesBySubjectId(id, mentoruserid,
                                                                                      currentPageIndex + 1,
                                                                                      DefaultPageSize, out totalcount);
            AdminSubjectsViewModel adminSubjectsViewModel = _subjectRepository.GetSubjectBySubjectId(id);
            AdminMentorsViewModel mentor = _mentorRepository.GetMentorByUserId(mentoruserid);

            quizListViewModel.SubjectName = adminSubjectsViewModel.SubjectCode;
            quizListViewModel.SubjectId = id;
            quizListViewModel.MentorUserId = mentoruserid;
            quizListViewModel.MentorId = mentor.MentorId;
            quizListViewModel.QuizViewModelList = quizViewModels.ToPagedList(currentPageIndex, DefaultPageSize, totalcount);

            return View(quizListViewModel);
        }


        public ActionResult Take(int id, int mentoruserid, int subjectid, int? page)
        {
            // if ((user.ConfirmationCodeExpiryDate.ToDate() - DateTime.Now).TotalHours > 0)

            int currentPageIndex = page.HasValue ? (page.Value <= 0 ? 0 : page.Value - 1) : 0;
            var questionListViewModel = new QuestionListViewModel();
            List<QuestionViewModel> questionViewModels = _quizRepository.GetQuestionsByQuizId(id);
            if (questionViewModels.Count < 1)
            {
                return RedirectToAction("Index", new { id = subjectid, mentoruserid = mentoruserid });
            }
            QuizViewModel quiz = _quizRepository.GetQuizByQuizId(id);
            QuizStudent quizStudent = _quizRepository.GetQuizStudent(id);
            if (quizStudent != null)
            {

                List<int> seeds = quizStudent.RandomKey.Split(',').Select(x => x.ToInteger()).ToList();
                questionViewModels.Shuffle(seeds);
                questionListViewModel.StudentId = quizStudent.StudentId;

                if (quizStudent.Done.ToBooleaan())
                {
                    return RedirectToAction("Index", new { id = subjectid, mentoruserid = mentoruserid });
                }
            }
            else
            {
                List<int> seed;
                questionViewModels.Shuffle(out seed);
                AdminStudentsViewModel student = _studentRepository.GetStudentByUserId((int)provider.User.UserId);
                int studentId = 0;
                if (student != null)
                {
                    studentId = student.StudentId;
                }
                quizStudent = new QuizStudent();
                quizStudent.StudentId = studentId;
                questionListViewModel.StudentId = studentId;
                quizStudent.QuizId = id;
                quizStudent.DateStarted = DateTime.Now;
                quizStudent.DateEnd = quizStudent.DateStarted.AddMinutes(quiz.TimeLimit);
                quizStudent.RandomKey = String.Join(",", seed);
                quizStudent.TotalItems = questionViewModels.Count;
                quizStudent = _quizRepository.AddQuizStudent(quizStudent);
            }

            //check if done before computing for time reamaining

            questionListViewModel.TimeRemaining = (quizStudent.DateEnd - DateTime.Now).TotalSeconds.ToInteger();
            questionListViewModel.TimeRemaining = questionListViewModel.TimeRemaining < 0 ? 0 : questionListViewModel.TimeRemaining;
            questionListViewModel.MentorUserId = mentoruserid;
            questionListViewModel.SubjectId = subjectid;
            questionListViewModel.QuizId = id;
            questionListViewModel.QuizStudentId = quizStudent.QuizStudentId;
            
            questionViewModels  = questionViewModels.Skip(0).Take(quiz.TotalItems).ToList();

            int totalcount = questionViewModels.Count;

            foreach (var question in questionViewModels)
            {
                QuestionsAnswer questionsAnswer = _quizRepository.GetQuestionAnswer(question.QuestionId, questionListViewModel.QuizStudentId);
                if (questionsAnswer != null)
                    question.Answer = questionsAnswer.ChoiceAnswerId;
            }

            questionListViewModel.QuestionViewModelList = questionViewModels.ToPagedList(currentPageIndex, 1, totalcount);

            if (questionListViewModel.TimeRemaining < 1)
            {
                _quizRepository.UpdateQuizStudentDone(quizStudent.QuizStudentId);
                return RedirectToAction("Index", new { id = subjectid, mentoruserid = mentoruserid });
            }

            return View(questionListViewModel);
        }

        [HttpPost]
        public ActionResult Take(int id, QuestionsViewModel questionListViewModel)
        {
            List<QuestionViewModel> questionViewModels = _quizRepository.GetQuestionsByQuizId(questionListViewModel.QuizId);
            int score = 0;
            foreach (QuestionViewModel question in questionListViewModel.QuestionViewModelList)
            {
                QuestionViewModel questionAnswers =
                    questionViewModels.FirstOrDefault(
                        x => (x.QuestionId == question.QuestionId && x.ChoiceIdAnswer == question.Answer));

                if (questionAnswers != null)
                {
                    score++;
                }
            }

            _quizRepository.UpdateQuizStudentScore(questionListViewModel.QuizStudentId, score);
            return RedirectToAction("Score", new { score = score });
        }

        [HttpPost]
        public ActionResult AdUpAnswer(int qid, int sid, int qzid)
        {

            return Content("OK");
        }

        public ActionResult Score(int score)
        {
            ViewData["score"] = score;
            return View();
        }


        [HttpPost]
        public ActionResult SaveAnswer(int choiceAnswerId, int quizStudentId, int questionId)
        {
            QuestionsAnswer questionsAnswer = new QuestionsAnswer();
            var student = _studentRepository.GetStudentByUserId((int)provider.User.UserId);
            questionsAnswer.StudentId = student.StudentId;
            questionsAnswer.ChoiceAnswerId = choiceAnswerId;
            questionsAnswer.QuizStudentId = quizStudentId;
            questionsAnswer.QuestionId = questionId;
            _quizRepository.AddQuestionAsnwer(questionsAnswer);
            return Content("Answer Saved");
        }

    }
}
